<template>
  <div v-if="isSpriteSheet" :class="getSpriteSheetClass" ref="img"
    :name="item.commonAttr.name"
    :alt="item.commonAttr.name"
    :style="imgSpriteSheetStyles_"></div>
  <van-image v-else-if="isLazyLoad && getImgUrl" class="wb-img" ref="img"
    :data-id="item.id"
    :lazy-load="true"
    @load="onImgLoaded"
    @click="onSelected"
    :src="getImgUrl"
    :name="item.commonAttr.name"
    :alt="item.commonAttr.name"
    :style="imgStyles_">
    <template v-slot:loading>
      <van-loading type="spinner" size="20" />
    </template>
  </van-image>
  <img v-else-if="!isLazyLoad && getImgUrl" class="wb-img" ref="img"
    :data-id="item.id"
    :crossOrigin="crossOriginStr"
    @load="onImgLoaded"
    @click="onSelected"
    :src="getImgUrl"
    :name="item.commonAttr.name"
    :alt="item.commonAttr.name"
    :style="imgStyles_"/>
</template>

<script>
import { utils } from '@/components/utils/utils'
import { commonUtils } from '@/components/utils/common-utils'
import { EventBus } from '@/store/index'
import { PAGE_TYPE } from '@/common/const'
import { COMPONENT_TYPES } from '@/common/const-wb'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { isWeibo, isJSON, getCompIdByParam } from '@/plugins/utils'
import { getPxOVwByValue, getPxOrVw } from '@/store/utils'
import { reactive } from 'vue'
import { isHasOwnProperty } from '@/plugins/utils'
import Rotate3dEvent from '@/components/events/Rotate3dEvent'

export default {
  mixins: [utils, commonUtils],
  setup (props) {
    const state = reactive({
      imgStyles_: {},
    });
    const state_ = {
      isRotate3dData: false,//3d旋转事件是数据类型的自动刷新
      isRefresh: false,
      imgUrl: '',
      imgSpriteSheetStyles_: {},
      isSelected: false,
      crossOriginStr: props.item.commonAttr.relateAttrCompId ? 'Anonymous' : ''
    }
    _.merge(state, state_)
    return state
  },
  created() {
    this.imgStyles()
    const commonAttr = this.commonAttr;
    if(commonAttr.isDynamic){
      this.imgUrl = '';
    }else{
      this.imgUrl = this.item.commonAttr.url;
    }
    if(this.isH5Edit){
      return
    }
    let rotate3dEvent = this.item.events.rotate3d;
    if(rotate3dEvent && (rotate3dEvent.mouseBehavior == "data")) {
      this.isRotate3dData = true
    }
    let relateAttrCompId = getCompIdByParam(commonAttr.relateAttrCompId);
    if(commonAttr.dataKey || relateAttrCompId || commonAttr.isDynamic || this.isRotate3dData){
      this.isRefresh = true;
      EventBus.$off("refreshDynamicData", this.onRefreshImgUrl);
      EventBus.$on("refreshDynamicData", this.onRefreshImgUrl);
    }

    if(this.item.interactionData && this.item.interactionData.spriteSheetObj){
      this.imgSpriteSheetStyles_ = reactive({
        width: 0,
        height: 0,
        background: '',
        backgroundPosition: '',
        backgroundRepeat: 'no-repeat',
        backgroundSize: '',
        animation: '',
      })
      EventBus.$off("playSpriteSheetAnim", this.onPlaySpriteSheetAnim);
      EventBus.$on("playSpriteSheetAnim", this.onPlaySpriteSheetAnim);
      EventBus.$off("refreshImgSpriteSheet", this.onRefreshImgSpriteSheet);
      EventBus.$on("refreshImgSpriteSheet", this.onRefreshImgSpriteSheet);

      if(!this.item.commonAttr.groupInjectClassName){
        let spriteSheetObj = this.item.interactionData.spriteSheetObj;
        this.onRefreshImgSpriteSheet({ id: this.item.id });
        if(spriteSheetObj.isAutoPlay){
          this.onPlaySpriteSheetAnim();
        }
      }
    }
    this.onRefreshImgUrl()

    if(this.item.commonAttr.groupInjectClassName){
      this.injectDomInCompData()
    }
    EventBus.$off("refreshImgStyles", this.onRefreshImgStyles);
    EventBus.$on("refreshImgStyles", this.onRefreshImgStyles);

    // if(!this.siteInfo.md.isIPhone && isWeibo() && this.commonAttr.isLongPressSaveImg){
    //   import(`@/components/events/LongPressEvent` /* webpackChunkName: "@/components/events/LongPressEvent" */).then((module) => {
    //     let longPressEvent = this.longPressEvent = new module.default();
    //     longPressEvent.excute({ item: this.item, vueContainer: this });
    //   })
    // }
  },
  computed: {
    getSpriteSheetClass(){
      let isCssFrameA = false;
      let isCssFrame = false;

      let spriteSheetObj = this.item.interactionData.spriteSheetObj;
      if(spriteSheetObj.duration > 0){
        isCssFrameA = true;
      }else{
        isCssFrame = true
      }
      let classes = [{
        'wb-img': true,
        'css-frame-a': isCssFrameA,
        'css-frame': isCssFrame,
      }];
      return classes;
    },
    isSpriteSheet(){
      return !this.isH5Edit && this.item.interactionData && this.item.interactionData.spriteSheetObj ? true : false;
    },
    isLazyLoad(){
      if(this.isH5Edit || this.siteAttrs.pageType == PAGE_TYPE.single || this.popId || this.commonAttr.isFullScreen ||
        this.siteAttrs.pageType == PAGE_TYPE.long && this.item.conAttr.top < MOBILE_WID_HEI.height){
        return false
      }else{
        return true
      }
    },
    getImgUrl(){
      if(this.isH5Edit){
        return this.commonAttr.url;
      }else{
        //relateAttrCompId 站点id 655 新年许愿管
        const commonAttr = this.commonAttr;
        if(commonAttr.isDynamic && this.shareData.url){
          return this.shareData.url;
        }
        if(this.isRefresh){
          return this.imgUrl;
        }else{
          if(this.popId && this.popId > 0 || this.pageId && this.pageId == this.pageIndex + 1){
            return commonAttr.url;
          }else{
            return '';
          }
        }
      }
    },
    link(){
      const commonAttr = this.commonAttr;
      if(isWeibo() && commonAttr.schemaLink && commonAttr.schemaLink.length > 0){
        return commonAttr.schemaLink
      }else{
        return commonAttr.link
      }
    },
  },
  mounted(){
    if(this.commonAttr.imgId){
      this.$refs.img.id = this.commonAttr.imgId
    }
    if(!this.isH5Edit){
      if(this.item.events.showOrHide){
        let event = this.item.events.showOrHide;
        const showOrHideStr = event.comps[0].attrs.value;
        if(showOrHideStr && isJSON(showOrHideStr)){
          const showOrHideObj = JSON.parse(showOrHideStr);
          if(showOrHideObj.delayTime > 0){
            window.setTimeout(() => {
              this.$store.commit("updateComponentAttr", {id: this.item.id, commonAttr: { isVisible: false } })
            }, showOrHideObj.delayTime * 1000)
          }
        }
      }
      this.convertCustomCss();
    }
  },
  methods: {
    getCompDom() {
      return this.$refs.img
    },
    onSelected(e) {
      // 1669 使用图片的选中状态 来判断是否播放 声音 跳转页面  playAudio这个前端事件中使用
      // let isPlay = this.item.commonAttr.isSelected_
      // EventBus.$emit("playOrPauseAudio", { isPlay, isTouch: true });
      // EventBus.$emit("playVideo");
      // gsap 动画的播放与暂停都是使用这个字段来判断的
      this.commonAttr.isSelected_ = this.isSelected = !this.isSelected;
      if(this.commonAttr.relateEventCompId){
        const relateEventCompId = getCompIdByParam(this.commonAttr.relateEventCompId);
        const compData = this.componentMap[relateEventCompId]
        compData.commonAttr.isSelected_ = this.commonAttr.isSelected_
      }
      // if(this.commonAttr.filter.isGrayscale){
      // //灰色 阻止事件冒泡
      //   e.stopPropagation();
      // }
    },
    onRefreshImgStyles({ id }) {
      if(id == this.item.id) {
        this.imgStyles()
      }
    },
    onRefreshImgSpriteSheet({ id }){
      //1535 css 序列图
      if(id == this.item.id) {
        let spriteSheetObj = this.item.interactionData.spriteSheetObj;
        this.imgSpriteSheetStyles_.width = getPxOVwByValue(spriteSheetObj.width);
        this.imgSpriteSheetStyles_.height = getPxOVwByValue(spriteSheetObj.height);
        this.imgSpriteSheetStyles_.background = `url(${spriteSheetObj.url})`;
        let currentStep = spriteSheetObj.currentStep > spriteSheetObj.steps ? spriteSheetObj.steps : spriteSheetObj.currentStep;
        this.imgSpriteSheetStyles_.backgroundPosition = `${getPxOVwByValue(-currentStep*spriteSheetObj.width)} 0`;
        this.imgSpriteSheetStyles_.backgroundSize = `${getPxOVwByValue(spriteSheetObj.width*spriteSheetObj.steps)} ${getPxOVwByValue(spriteSheetObj.height)}`;

        this.$nextTick(() => {
          let dom = document.getElementById(this.item.id);
          if(dom && isHasOwnProperty(spriteSheetObj, "scale")) {
            dom.style['transform-origin'] = 'center center';
            dom.style['transform'] = 'scale(' + spriteSheetObj.scale + ')';
            // dom.style['overflow'] = 'hidden';
          }
        })
      }
    },
    onPlaySpriteSheetAnim(){
      let spriteSheetObj = this.item.interactionData.spriteSheetObj;
      if(spriteSheetObj.duration > 0){
        //修改main.css中的:root里的变量
        document.documentElement.style.setProperty(`--css-animate-position-x`, getPxOVwByValue(-spriteSheetObj.steps*spriteSheetObj.width));
        this.imgSpriteSheetStyles_["-webkit-animation"] = `css-frame-animation ${spriteSheetObj.duration}s steps(${spriteSheetObj.steps}) infinite}`;
        this.imgSpriteSheetStyles_["animation"] = `css-frame-animation ${spriteSheetObj.duration}s steps(${spriteSheetObj.steps}) infinite}`;
      }
      window.setTimeout(() => {
        this.imgSpriteSheetStyles_.animation = '';
        if(!this.interactionData.isEmit){
          this.interactionData.isEmit = true;
          EventBus.$emit("playGroupSpriteSheetAnim", { item: this.item });
        }
      }, spriteSheetObj.duration*1000)
    },
    onImgLoaded(){
      if(this.isH5Edit){
        return
      }
      this.item.commonAttr.isLoadedImg = true;
    },
    onRefreshImgUrl(){
      if(this.isH5Edit){
        return
      }
      let url = this.imgUrl;
      const commonAttr = this.commonAttr;
      const relateAttrCompId = getCompIdByParam(commonAttr.relateAttrCompId);
      let relateComponentData = this.componentMap[relateAttrCompId];

      if(commonAttr.dataKey){
        let url_;
        if(relateAttrCompId && relateComponentData) {
          url_ = this.getDataKeyValue(relateComponentData);
        } else if(commonAttr.dataKey == "custom") {
          url_ = this.getAttrByCustom(this.item);
        }
        if(url_){
          url = url_;
        }
      }else if(relateAttrCompId && relateComponentData){
        if(relateComponentData.cid == COMPONENT_TYPES.wb_camera){
          //wb-camera 截图传过来的值 站点id 654 王一博 的壁纸女孩
          let url_ = relateComponentData.commonAttr.cropImgUrl || relateComponentData.commonAttr.url;
          if(url_){
            url = url_;
          }
        }
      }else if(this.isRotate3dData){
        //数据来自自身，随机一个索引 获取一个图片，不能使用自定义数据 703 3d旋转随机获取一个图片后截图保存给发博提供数据
        let rotate3dEvent = this.item.events.rotate3d;
        let eventFunc = new Rotate3dEvent();
        url = eventFunc.excute({item:this.item, event:rotate3dEvent, isPostWbEventOrCommonEvents: null})
        eventFunc.destroy();
      }
      // 动态文本 也可以从图片name中获取键值，或者是默认的shareData中的url
      if(commonAttr.isDynamic && this.shareData.url){
        url = this.shareData.url;
      }
      this.imgUrl = url;
    },
    imgStyles(){
      let styles_ = null;
      if(this.isH5Edit) {
        styles_ = this.getStyles();
      }else{
        styles_ = this.styles;
      }
      if(this.commonAttr.isFullScreen && this.commonAttr.objectFit){
        styles_.objectFit = this.commonAttr.objectFit;
      }

      // 是否可以在app端长按保存图片 需要判断整个站点是否能够进行长按保存
      if(this.siteAttrs && this.siteAttrs.isNotSaveImg && !this.commonAttr.isSaveImg){
        styles_['pointer-events'] = 'none'
        styles_[' -webkit-user-select'] = 'none'
      }

      let commonAttr = this.item.commonAttr
      let unit = getPxOrVw()
      if(commonAttr.isGradient){
        let str = '-webkit-linear-gradient(' + commonAttr.gradientDirection + ', '
        let gradientColors = commonAttr.gradientColors.split(',')
        let len = gradientColors.length
        let base = 1/len * 100

        _.forEach(gradientColors, (color, index) => {
          if(index == len-1){
            str += color + ' ' + index * base + '%'
          }else{
            str += color + ' ' + index * base + '%, '
          }
        })
        str += ')'
        styles_.backgroundImage = str
      }

      if(commonAttr.filter){
        let filter = commonAttr.filter
        let filterStr = ''
        if(filter.isBlur){
          if(filterStr.length > 0){
            filterStr += ' '
          }
          filterStr += 'blur('+filter.blur+''+unit+')'
        }
        if(filter.isBrightness){
          if(filterStr.length > 0){
            filterStr += ' '
          }
          filterStr += 'brightness('+filter.brightness+')'
        }
        if(filter.isContrast){
          if(filterStr.length > 0){
            filterStr += ' '
          }
          filterStr += 'contrast('+filter.contrast+')'
        }
        if(filter.isShadow){
          if(filterStr.length > 0){
            filterStr += ' '
          }
          let offsetX = filter.offsetX + unit
          let offsetY = filter.offsetY + unit
          let blurRadius = filter.blurRadius + unit
          // let spreadRadius = filter.spreadRadius + unit
          let shadowColor = filter.shadowColor
          filterStr += 'drop-shadow('+offsetX+' '+offsetY+' '+blurRadius+' '+shadowColor+')'
        }
        if(filter.isGrayscale){
          if(filterStr.length > 0){
            filterStr += ' '
          }
          filterStr += 'grayscale('+filter.grayscale+')'
        }
        if(filter.isHueRotate){
          if(filterStr.length > 0){
            filterStr += ' '
          }
          filterStr += 'hue-rotate('+filter.hueRotate+'deg)'
        }
        if(filter.isInvert){
          if(filterStr.length > 0){
            filterStr += ' '
          }
          filterStr += 'invert('+filter.invert+')'
        }
        if(filter.isSaturate){
          if(filterStr.length > 0){
            filterStr += ' '
          }
          filterStr += 'saturate('+filter.saturate+')'
        }
        if(filter.isSepia){
          if(filterStr.length > 0){
            filterStr += ' '
          }
          filterStr += 'sepia('+filter.sepia+')'
        }
        styles_['-webkit-filter'] = filterStr
      }
      this.imgStyles_ = styles_
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },
    onRefreshCommonAttr() {
      this.imgStyles();
    },
  },
  beforeUnmount(){
    if(this.isH5Edit){
      EventBus.$off('refreshCommonAttr', this.onRefreshCommonAttr);
      return
    }
    this.item.vueContainer = null;
    this.commonAttr.isSelected_ = this.isSelected = false;
    if(this.isRefresh){
      EventBus.$off("refreshDynamicData", this.onRefreshImgUrl)
    }
    this.isRefresh = false;
    if(this.item.interactionData && this.item.interactionData.spriteSheetObj){
      EventBus.$off("playSpriteSheetAnim", this.onPlaySpriteSheetAnim);
      EventBus.$off("refreshImgSpriteSheet", this.onRefreshImgSpriteSheet);
    }
    this.item.commonAttr.isLoadedImg = false;
    this.imgUrl = '';
    this.imgStyles_ = {};
    this.imgSpriteSheetStyles_ = {};

    if(this.longPressEvent){
      this.longPressEvent.destroy();
    }
    EventBus.$off("refreshImgStyles", this.onRefreshImgStyles);

  }
};
</script>
<style lang="scss">
.wb-img {
  width: inherit;
  height: inherit;
  display: block;

  img{
    opacity: inherit;
    border-radius: inherit;
  }

  .blur {
      -webkit-filter: blur(4px);
      filter: blur(4px);
  }

  .brightness {
      -webkit-filter: brightness(0.30);
      filter: brightness(0.30);
  }

  .contrast {
      -webkit-filter: contrast(180%);
      filter: contrast(180%);
  }

  .grayscale {
      -webkit-filter: grayscale(100%);
      filter: grayscale(100%);
  }

  .huerotate {
      -webkit-filter: hue-rotate(180deg);
      filter: hue-rotate(180deg);
  }

  .invert {
      -webkit-filter: invert(100%);
      filter: invert(100%);
  }

  .opacity {
      -webkit-filter: opacity(50%);
      filter: opacity(50%);
  }

  .saturate {
      -webkit-filter: saturate(7);
      filter: saturate(7);
  }

  .sepia {
      -webkit-filter: sepia(100%);
      filter: sepia(100%);
  }
}

</style>
